﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;
using System.Xml.Linq;
using System.Text.RegularExpressions;

namespace Chip8
{
    public class clsCheats
    {
        public void CreateXML()
        {
            StreamWriter sr = new StreamWriter("Cheats.cht");
            sr.WriteLine("<Cheats>");
            sr.WriteLine("</Cheats>");
            sr.Close();
        }

        public void AddNewCheatXML(string CheatTitle, string Cheat, string MD5, string ID, string FileName)
        {
            if (!File.Exists("Cheats.cht"))
                CreateXML();

            XDocument doc = XDocument.Load("Cheats.cht");
            XElement root = new XElement("CheatInfo");
            root.Add(new XAttribute("MD5", MD5));
            root.Add(new XAttribute("ID", ID));
            root.Add(new XAttribute("FileName", FileName));
            root.Add(new XElement("CheatTitle", CheatTitle));
            root.Add(new XElement("Cheat", Cheat));
            doc.Element("Cheats").Add(root);
            doc.Save("Cheats.cht"); 
        }

        public void UpdateCheatXML(string MD5, string ID, string Title, string Cheat)
        {
            if (!File.Exists("Cheats.cht"))
                CreateXML();

            XDocument doc = XDocument.Load("Cheats.cht");
            IEnumerable<XElement> nodes =
                                 from node in doc.Root.Elements("CheatInfo")
                                 let md5 = node.Attribute("MD5")
                                 let id = node.Attribute("ID")
                                 where md5 != null && id != null && md5.Value == MD5 && id.Value == ID
                                 select node;
            if (nodes.Count() != 0)
            {
                foreach (XElement el in nodes)
                {
                    el.Element("CheatTitle").SetValue(Title);
                    el.Element("Cheat").SetValue(Cheat);
                }
            }
            doc.Save("Cheats.cht");
        }

        public void DeleteCheatXML(string MD5, string ID)
        {
            if (!File.Exists("Cheats.cht"))
                CreateXML();

            XDocument doc = XDocument.Load("Cheats.cht");
            var q = from node in doc.Descendants("CheatInfo")
                    let md5 = node.Attribute("MD5")
                    let id = node.Attribute("ID")
                    where md5 != null && id != null && md5.Value == MD5 && id.Value == ID
                    select node;
            q.ToList().ForEach(x => x.Remove());
            doc.Save("Cheats.cht");
        }
    }
}
